package com.yuntuzhilian.chapter5.demo2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author MrWang-shuizhishuiheshui
 * @description 服务器--提供服务
 */
public class ServerTest {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket =null;
        InputStream inputStream=null;
        OutputStream outputStream=null;
        ObjectInputStream objectInputStream=null;
        try {
            //1创建ServerSocket对象,指定端口号
            serverSocket=new ServerSocket(8000);
            //2.监听客户端的请求
            socket = serverSocket.accept();
            //3.打开输入流,处理请求过来的数据信息
            inputStream = socket.getInputStream();
            //  创建输出流,给客户端响应信息
            outputStream = socket.getOutputStream();

            //4.处理输入流中的信息
            //将输入流转化为对象输入流
            objectInputStream=new ObjectInputStream(inputStream);
            Student stu=(Student)objectInputStream.readObject();
            System.out.println("我是服务器,我接受客户端的数据为:"+stu.toString());
            //将socket中的输入流关闭
            socket.shutdownInput();

            //5.服务器给客户端响应
            String str="服务器收到你的信息,谢谢你对象的登录!";
            outputStream.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            try {
                objectInputStream.close();
                inputStream.close();
                outputStream.close();
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
